/*
 * @message: 描述
 * @Author: Roy
 * @Email: cx_love_xc@163.com
 * @Github: cx_love_xc@163.com
 * @Date: 2022-01-14 14:52:50
 * @LastEditors: Roy
 * @LastEditTime: 2022-01-17 17:32:37
 * @Deprecated: 否
 * @FilePath: /blog/src/admin/container/store/reducer.js
 */
import { produce, original } from 'immer'
// import { parseJsonByString } from '../../../common/util'
import { CHANGE_SCHEMA, ADD_PAGE_CHILDREN, CHANGE_PAGE_CHILD, DELETE_PAGE_CHILD, CHANGE_PAGE_CHILD_POSITION, CHANGE_PAGE_ATTRIBUTE } from './constant';

// const initialSchema = parseJsonByString(localStorage.schema, {
//     name: 'Page',
//     attributes: {},
//     children: []
// });
const initialSchema = {
    name: 'Page',
    attributes: {},
    children: []
};

const defaultState = {
    schema: initialSchema
}


const commonReducer = (state = defaultState, action) => produce(state, (draft) => {
    switch (action.type) {
        case CHANGE_SCHEMA:
            draft.schema = action.value;
            break;
        case ADD_PAGE_CHILDREN:
            draft.schema.children.push(action.value);
            break;
        case CHANGE_PAGE_CHILD:
            draft.schema.children.splice(action.index, 1, action.value);
            break;
        case DELETE_PAGE_CHILD:
            draft.schema.children.splice(action.index, 1);
            break;
        case CHANGE_PAGE_CHILD_POSITION:
            const copy = original(draft.schema.children);
            draft.schema.children.splice(action.oldIndex, 1);//返回的是一个proxy类型
            draft.schema.children.splice(action.newIndex, 0, copy[action.oldIndex]);
            break;
        case CHANGE_PAGE_ATTRIBUTE:
            draft.schema.attributes[action.key] = action.value;
            break;
        default:
            break;
    }
})

export default commonReducer